<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '基础信息' },
          { name: 'box-list', title: '备货明细' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <div id="box-base" class="box-title">基础信息</div>
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <customFormItem
          label="申请科室" name="deptName" :parent="_self" :form="form"
          :readonly="true" :showSelectIcon="true" @focus="utilSelect.dept(deptIdChange)"
        />

        <customFormItem
          label="供应商" name="supplierName" :parent="_self" :form="form"
          :readonly="true"
          :showSelectIcon="true"
          @focus="utilSelect.supplier(supplierChange)"
          :disabled="propReadonly"
          help="保存后不可修改"
        />
        <customFormItem
          label="申领单号" name="oprtApplyKey" :parent="_self"
          :form="form" :type="constCommon.formItemType.staticHtml.name"
          :config="{defaultValue: '自动获取'}"
        />
        <customFormItem
          label="申领日期" name="oprtApplyDate" :parent="_self" :form="form"
          :type="constCommon.formItemType.datePicker.name" :config="{defaultValue: '自动获取'}" disabled
        />
        <customFormItem
          label="申请人" name="oprtApplyUser" :parent="_self" :form="form"
          ::config="{defaultValue: '自动获取'}" disabled
        />
        <customFormItem
          label="申请仓库" name="warehouseNameFrom" :parent="_self" :form="form"
          :readonly="true" :showSelectIcon="true"
          @focus="utilSelect.warehouse(fromWarehouseChange)"
        />
        <customFormItem
          label="配送仓库" name="warehouseNameTo" :parent="_self" :form="form" disabled
        />
        <customFormItem
          label="手术单号" name="oprtCode" :parent="_self" :form="form"
          v-if="cpIsOprtApplyType1"
          appendBtn
        >
          <template #appendBtn>
            <customButton
              title="选择"
              theme="success"
              @click="utilSelect.oprt(oprtChange)"
              v-show="!propReadonly && cpIsOprtApplyType1"
            >
            </customButton>
          </template>
        </customFormItem>
        <customFormItem
          label="手术名称" name="oprtName" :parent="_self" :form="form"
          v-if="cpIsOprtApplyType1"
        />
        <customFormItem
          label="患者" name="patientName" :parent="_self" :form="form"
          v-if="cpIsOprtApplyType1"
          appendBtn
        >
          <template #appendBtn>
            <customButton
              title="选择"
              theme="success"
              @click="utilSelect.patient(patientChange)"
              v-show="!propReadonly && cpIsOprtApplyType1"
            >
            </customButton>
          </template>
        </customFormItem>
        <customFormItem
          label="患者年龄" name="patientAge" :parent="_self" :form="form"  :type="constCommon.formItemType.inputNumber.name"
          v-if="cpIsOprtApplyType1"
        />
        <customFormItem
          label="床位号" name="bedNo" :parent="_self" :form="form"
          v-if="cpIsOprtApplyType1"
        />
        <customFormItem
          label="住院编号" name="patientNo" :parent="_self" :form="form"
          v-if="cpIsOprtApplyType1"
        />
        <customFormItem
          label="主治医生" name="docNameSug" :parent="_self" :form="form"
          v-if="cpIsOprtApplyType1"
        />
        <customFormItem
          label="专家" name="docNameApply" :parent="_self" :form="form"
          v-if="cpIsOprtApplyType1"
        />

        <customFormItem label="备注" name="remark"  :parent="_self" :form="form" />
      </customForm>

      <div id="box-list" class="box-title">备货明细</div>
      <data-view
        propViewKey="dept_oprt_apply_item"
        :propInitData="form"
        ref="childDataView"
        @after-load="afterLoad"
        @view-ready="viewReady"
        @edit-input="editInput"
        @extra-button-click="extraButtonClick"
        @select-change="selectChange"
        :propTableHide="propParent.cpFormNew"
        propTableHideMsg="请先保存主单据再操作"
        :propBeforeClick="propBeforeClickDtl"
        @customSelectFocus="customSelectFocus"
        :propNoEditRow="true"
        propEditConfigMode="cell"
        :propHideFlowSelect="true"
        :propChildTableStyle="{marginLeft: '80px'}"
        :propActiveRowMethod="propActiveRowMethod"

        :propFlowKey="propParent.propFlowKey"
        :propParentPage="_self"
        :propAutoFetchData="false"
        :propParentData="propParent.viewFormData"
        :propFilterBtn="propFilterBtn"
      />

    </div>
  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'

export default {
  data() {
    return {
      form: {},
      viewData: {},
      saveByAddRow: false, //是否添加明细保存的
      selectWarehouseColumns: [
        {
          name: 'name',
          label: '仓库名称',
          width: 150,
          search: true
        },
        {
          name: 'address',
          label: '仓库地址',
          span: 200,
          search: true
        }
      ],
      selectMatrColumns: [
        { title: '供应商名称', field: 'supplierName', width: 200, search: true },
        { title: '品名', field: 'name', width: 200, search: true },
        { title: '品规', field: 'spec', width: 200, search: true },
        { title: '厂商名称', field: 'mfgName', search: true },
        { title: '单品单位', field: 'skuUnit', width: 80, search: false },
        { title: '单品单价', field: 'skuPrice', width: 80, search: false },
        { title: '库存数量', field: 'stockCount', width: 80 }
      ],
      formReadOnly: false, //是否只读
      templetDialogVisible: false,
      propPackType: 'oper_apply',
      defaultInput: [//其他默认信息输入

      ],
      activeNames: ['1']
    }
  },
  methods: {


    // 科室选择
    deptIdChange(item) {
      this.$set(this.form, 'deptId', item.id)
      this.$set(this.form, 'deptName', item.name)
    },

    // 仓库选择
    fromWarehouseChange(row) {
      this.$set(this.form, 'warehouseIdFrom', row.id)
      this.$set(this.form, 'warehouseNameFrom', row.name)
    },
    //行编辑普通input框的修改事件，比如修改耗材包的数量后自动更新基本单位的数量
    editInput({ row, column }) {
      //修改完包装数量，修改单品数量和金额
      if (column.property == 'packageQty') {
        this.$set(row, 'skuQty', row.packageRate * row.packageQty)
        this.$set(row, 'amount', this.utilNum.toFixed(row.skuPrice * row.skuQty))
      }
    },
    afterLoad() {
      this.syncMatrUnit()
    },

    // 列表按钮点击前操作
    propBeforeClickDtl(button, formData , rowData, that) {
      //列表添加按钮
      if (button.key == this.constCommon.btnKeyMap.table.add) {
        this.utilSelect.matrMore(
          this.matrSelect,
          {
            warehouseIdStock: this.form.warehouseIdTo
          },
          this.form.supplierId,
          null,
          true,
          true
        )
        return false
      }
      return true
    },
    // 商品选择后
    matrSelect(rows, refName) {
      //转换属性
      rows.forEach(ob => {
        ob.id = null
        ob.matrType = 0
        ob.status = 0
        ob.oprtApplyId = this.form.id

        //包装信息
        ob.packageUnit = ob.skuUnit
        ob.packageRate = 1
        ob.packageQty = 1
        ob.skuQty = 1
        ob.amount = this.utilNum.toFixed(ob.skuPrice * ob.skuQty)
      })

      //批量添加
      this.utilVue.loadShow(true)
      this.$ajax.post('/dept/oprt_apply_item/saveBatch', rows).then(resp => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
          this.fetchChildData()
        }
      })
    },
    viewReady() {
      this.syncMatr()
    },
    //行编辑选择事件
    selectChange(param) {
      if (param.column.property == 'packageUnit') {
        this.matrUnitChangeEvent(param.row, param.column.selectRow)
      } else if (param.column.property == 'matrName') {
        this.addDtlBatch(param)
      }
    },
    async extraButtonClick({ button, data, index }) {
      let { key: buttonKey } = button
      if (buttonKey === 'oper_apply') {
        this.utilSelect.matrPackTempletMore(this.packSelect, this.form.deptId, this.constCommon.dictType.tempTypeOperBag, this.form.supplierId)
      }
    },
    //耗材单位选择事件
    matrUnitChangeEvent(row, packageUnit) {
      packageUnit && this.$set(row, 'packageUnit', packageUnit.packageUnit)
      && this.$set(row, 'packageRate', packageUnit.packageRate)
      && this.$set(row, 'skuQty', this.utilNum.toFixed(packageUnit.packageRate * row.packageQty))
      && this.$set(row, 'amount', this.utilNum.toFixed(packageUnit.packagePrice * row.packageQty))
    },
    getChildViewQueryWrapper() { //获取添加和编辑当前行id
      if (this.form.id) {
        return this.$newWrapper().eq('oprtApplyId', this.form.id).isNull('packId')
      } else {
        return this.$newWrapper().ne(1, 1)
      }
    },
    syncMatr() {
    },
    //耗材单位初始化
    syncMatrUnit() {
      //wrapper条件
      let wrapper = this.$newWrapper()
        .eq('flagApply', true)
      this.$refs.childDataView.setEditQueries('packageUnit', wrapper)

      //固定数据筛选参数
      let userParam = {
        viewKey: 'select_matr_unit_purchase',
        checkType: 'radio',
        useMsg: '数据筛选条件：所选耗材的有效请领单位',

        //前一个编辑单元格字段名
        beforeFieldEditName: 'matrName',
        //前一个单元格编辑值为空的提示
        beforeNullMsg: '请先选择耗材',
        //查询单位时的条件字段
        beforeFieldQueryName: 'matrId',
        //下一个编辑单元格
        nextFieldEditName: 'packageQty'
      }
      this.$refs.childDataView.setEditUserParam('packageUnit', userParam)
    },
    fetchChildData() {
      let newWrapper = this.$newWrapper()
      if (this.form.id) {
        newWrapper.eq('oprtApplyId', this.form.id)
      } else {
        newWrapper.ne(1, 1)
      }
      this.$refs.childDataView.setQueryWrapper(newWrapper)
    },
    async confirmCheck(rows) { //包确认选择事件钩子
      if (!this.form.id && this.form.id == null) {
        this.saveByAddRow = true
        await this.propParent.ocAsynSaveViewForm()
      }
      if (!rows.length) {
        return
      }
      let params = {
        oprtApplyId: this.form.id,
        packTemplets: rows
      }
      this.$ajax.post('/dept/oprt_apply_item/addByTemp', params).then(response => {
        response.success && this.utilMessage.success(response.msg)
        this.templetDialogVisible = false
        this.fetchChildData()
      })
    },
    //批量添加明细
    async addDtlBatch(param) {
      if (!this.form.id && this.form.id == null) {
        this.saveByAddRow = true
        await this.propParent.ocAsynSaveViewForm()
      }
      if (!this.form.id) {
        return
      }

      //多选，则为新增
      if (param.rows) {
        //转换属性
        let applyItem = []
        param.rows.forEach(ob => {
          ob.matrId = ob.id
          ob.matrName = ob.name
          ob.matrSpec = ob.spec
          ob.id = null
          ob.status = 0
          ob.oprtApplyId = this.form.id

          //包装信息
          ob.packageUnit = ob.packageUnitApply
          ob.packageQty = 1
          ob.skuQty = ob.packageRateApply
          ob.amount = this.utilNum.toFixed(ob.skuPrice * ob.skuQty)
          ob.packageRate = ob.packageRateApply
          applyItem.push(ob)
        })

        //批量添加
        this.utilVue.loadShow(true)
        this.$ajax.post('/dept/oprt_apply_item/saveBatch', applyItem).then(resp => {
          if (resp.code == 0) {
            this.utilMessage.success(resp.msg)
            this.fetchChildData()
          }
          this.utilVue.loadHide()
        })
      } else { //编辑
        let selectRow = param.column.selectRow
        param.row.matrId = selectRow.id
        param.row.matrName = selectRow.name
        param.row.matrSpec = selectRow.spec
        param.row.status = 0
        param.row.oprtApplyId = this.form.id

        //包装信息
        param.row.packageRate = selectRow.packageRateApply
        param.row.packageUnit = selectRow.packageUnitApply
        if (!param.row.packageQty) param.row.packageQty = 1

        //单品信息
        param.row.skuQty = selectRow.packageRateApply * param.row.packageQty
        param.row.skuPrice = selectRow.skuPrice
        param.row.skuUnit = selectRow.skuUnit
        param.row.amount = this.utilNum.toFixed(param.row.skuPrice * param.row.skuQty)
      }
    },
    // 自定义选择聚焦回调
    customSelectFocus(column, row) {
      // 包装名称
      if (column.name == 'packageUnit') {
        if (this.strings.isBlank(row.matrId)) {
          this.utilMessage.warning('请先选择商品')
          return
        }
        this.utilSelect.matrUnit(this.packageUnitSelect, row.matrId, true, false)
      }
    },
    // 单位选择后
    packageUnitSelect(row, refName) {
      // 当前选中行
      let currentRow = this.$refs.childDataView.getCurrentRow()
      //其他入库
      this.$set(currentRow, 'skuPrice', row.skuPrice)
      this.$set(currentRow, 'packageUnit', row.unit)
      this.$set(currentRow, 'packageRate', row.rate)
      this.$set(currentRow, 'skuQty', this.utilNum.toFixed(row.rate * currentRow.packageQty))
      this.$set(currentRow, 'amount', this.utilNum.toFixed(row.price * currentRow.packageQty))
    },

    // 模板选择后
    packSelect(rows, formData) {
      this.utilVue.loadShow(true)
      let params = {
        oprtApplyId: this.form.id,
        packTemplets: rows
      }
      this.$ajax.post('/dept/oprt_apply_item/addByTemp', params).then(response => {
        this.utilVue.loadHide()
        response.success && this.utilMessage.success(response.msg)
        this.fetchChildData()
      })
    },

    // 模板选择后
    propActiveRowMethod(column, row) {
      // 当前行，是包模板时，禁用包装单位选择
      if ('1' == row.matrType && column.property == 'packageUnit') {
        return false
      }
      return true
    },

    // 过滤显示按钮
    propFilterBtn(btnList) {
      // 只读时
      if (this.propReadonly) {
        return btnList.filter(btn => !['oper_apply'].includes(btn.code))
      }
      return btnList
    },
    // 手术单号 选择
    oprtChange(row) {
      this.$set(this.form, 'patientName', row.patientName)
      this.$set(this.form, 'oprtCode', row.code)
      this.$set(this.form, 'oprtName', row.name)
      this.$set(this.form, 'patientId', row.patientId)
      this.$set(this.form, 'patientAge', row.patientAge)
      this.$set(this.form, 'bedNo', row.bedNo)
      this.$set(this.form, 'patientNo', row.inpatientNo)
      this.$set(this.form, 'oprtDate', row.date)
      this.$set(this.form, 'docNameApply', row.doctorNameApply)
      this.$set(this.form, 'docNameSug', row.doctorNameSug)
      this.$set(this.form, 'oprtId', row.id)
    },
    //患者选择后
    patientChange(row) {
      this.$set(this.form, 'patientId', row.id)
      this.$set(this.form, 'patientName', row.name)
      this.$set(this.form, 'patientAge', row.age)
      this.$set(this.form, 'bedNo', row.bedNo)
      this.$set(this.form, 'patientNo', row.no)
    },
    // 供应商选择
    supplierChange(row) {
      this.$set(this.form, 'supplierId', row.id)
      this.$set(this.form, 'supplierName', row.name)
    }
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        if (!this.form.id) {
          this.$set(this.form, 'oprtApplyType', this.cpOprtApplyType)
          this.$set(this.form, 'deptId', this.utils.getCurrentUser().deptId)
          this.$set(this.form, 'deptName', this.utils.getCurrentUser().deptName)
          this.$set(this.form, 'oprtApplyUser', this.utils.getCurrentUser().name)
          this.$set(this.form, 'oprtApplyDate', new Date().format(this.dates.defaultDatePattern))
          let currentWarehouse = this.utils.getCurrentWarehouse()
          if (currentWarehouse && currentWarehouse.applyWarehouseId) {
            this.$set(this.form, 'warehouseNameFrom', currentWarehouse.warehouseName)
            this.$set(this.form, 'warehouseIdFrom', currentWarehouse.warehouseId)
            this.$set(this.form, 'warehouseNameTo', currentWarehouse.applyWarehouseName)
            this.$set(this.form, 'warehouseIdTo', currentWarehouse.applyWarehouseId)
          }
        }
        this.fetchChildData()
      },
      afterSave: () => {
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (flowButtonKey) => {
      },
      beforeClose: () => {
        return true
      },
      async afterClick(button, data, viewForm) {
        let {key: buttonKey} = button
        if (buttonKey == 'preview') {
          let param = {
            'that': that, //当前调用对象
            configList: [ //打印配置，可以多个
              {
                //打印配置
                printBusType: 'oprtDist', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData: that.form, //数据对象
                formDataId: that.form.id,
              }
            ]
          }
          global.utilPrint.openFormPrint(param)
        }
      },
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
    propParentPage: Object
  },
  components: {
    customAnchor
  },
  computed: {
    cpChildViewQueryWrapper() {
      let queryWrapper = this.$newWrapper()
      if (this.form.id) {
        queryWrapper.eq('oprtApplyId', this.form.id)
      } else {
        queryWrapper.ne(1, 1)
      }
      return queryWrapper
    },

    // 是否是手术备货申请
    cpOprtApplyType() {
      return this.propInitData.oprtApplyType
    },

    // 是否是手术备货申请
    cpIsOprtApplyType1() {
      return this.cpOprtApplyType == this.constCommon.dictType.oprtApplyTypeOprt
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
}
</style>
